Imports System.Windows.Forms

Public Class frmJournal

    ''' <summary>
    ''' Type of journal entry (no more than 10 characters)
    ''' </summary>
    Public Enum enumJournalEntry
        CreateTbl
        DeleteTbl
        Validate
        Transfer
        Delete
        Change
        Convert
        Edit
        Calculate
        Import
        DataEntry
        Download
        Append
        OwnerChg
        Archive
        Restore
        Upgrade
        EditTrk
        Misc
    End Enum

#Region "Routines to Manage Journal Entries..."

    ''' <summary>
    ''' Add a journal entry with the specified values; if global setting to automatically prompt for description is set, will do so
    ''' </summary>
    ''' <param name="TableName">Name of table</param>
    ''' <param name="EntryType">Type of journal entry</param>
    ''' <param name="RecordCount">Number of affected records</param>
    ''' <param name="Description">Description (if blank, may revert to prior value set using GetJournalDescription)</param>
    ''' <param name="DataSource">Source of data (usually import file; defaults to nothing)</param>
    ''' <param name="UserInit">Initials of user (defaults to initials in preferences)</param>
    ''' <param name="TimeStamp">Date-time value (defaults to Now)</param>
    ''' <param name="SkipAutoPrompt">If true, will ignore preference settings to always prompt for more journal information</param>
    ''' <remarks></remarks>
    Public Shared Sub AddJournalEntry(TableName As String, EntryType As enumJournalEntry, RecordCount As Integer,
                                       Optional Description As String = "", Optional DataSource As String = "",
                                       Optional UserInit As String = "", Optional TimeStamp As Date = Nothing,
                                       Optional SkipAutoPrompt As Boolean = False)
        If Description = "" Then Description = JournalDescription 'may have set description prior to adding journal entry (in dialog box)
        JournalDescription = ""

        If Description = "" AndAlso
           Not SkipAutoPrompt AndAlso
           (MainWRDB.PromptJournal = clsWRDB.enumJournalPrompt.Always OrElse
           (MainWRDB.PromptJournal >= clsWRDB.enumJournalPrompt.Import AndAlso EntryType = enumJournalEntry.Import) OrElse
           (MainWRDB.PromptJournal >= clsWRDB.enumJournalPrompt.Validate_Transfer AndAlso (EntryType = enumJournalEntry.Validate OrElse EntryType = enumJournalEntry.Transfer)) OrElse
           EntryType = enumJournalEntry.Misc) Then
            'display this form allowing the user to enter the description
            With New frmJournal
                If EntryType <> enumJournalEntry.Misc Then 'hide cancel button and change OK to Close (will always make journal entry)
                    .btnCancel.Visible = False
                    .btnOK.Text = "Close"
                    .CancelButton = .btnOK
                End If

                .txtTableName.Text = TableName
                .cboJournalType.Items.AddRange([Enum].GetNames(GetType(enumJournalEntry)))
                .cboJournalType.Text = EntryType.ToString
                .txtTimeStamp.Text = CDate(TestNull(TimeStamp, Now)).ToString(MyDateTimeFormat)
                .txtUserInit.Text = TestNull(UserInit, clsApplicationSettings.UserName)
                .txtDescription.Text = Description
                .txtSource.Text = DataSource
                .txtNumRec.Text = RecordCount.ToString("N0")
                .chkHideForm.Visible = EntryType <> enumJournalEntry.Misc
                If .ShowDialog(MainForm) = Windows.Forms.DialogResult.OK Then
                    TableName = Strings.Left(.txtTableName.Text, 100)
                    EntryType = [Enum].Parse(GetType(enumJournalEntry), .cboJournalType.Text)
                    TimeStamp = CDate(.txtTimeStamp.Text)
                    UserInit = Strings.Left(.txtUserInit.Text, 3)
                    Description = Strings.Left(.txtDescription.Text, 255)
                    DataSource = Strings.Left(.txtSource.Text, 255)
                    RecordCount = .txtNumRec.Text
                    .Dispose()
                Else
                    .Dispose()
                    Exit Sub
                End If
            End With
        End If

        With Project.DB
            Dim num As Integer = .ExecuteScalar($"SELECT COUNT(*) FROM {Project.FullTableName(clsProject.enumTableTypes.Journal)} Journal 
                                                  WHERE Table_Name={ .TextString(Strings.Left(TableName, 100))} 
                                                  AND Time_Stamp={ .DateTime(TestNull(TimeStamp, Now))}")
            If num > 0 Then Exit Sub 'avoid duplicate key errors
            Dim sql As String = String.Format("INSERT INTO {7} 
                                                (Table_Name, Time_Stamp, User_Init, Entry_Type, Description, Source, Record_Count) 
                                                VALUES ({0}, {1}, {2}, {3}, {4}, {5}, {6})",
                                                  .TextString(Strings.Left(TableName, 100)),
                                                  .DateTime(TestNull(TimeStamp, Now)),
                                                  .TextString(Strings.Left(TestNull(UserInit, clsApplicationSettings.UserName), 3)),
                                                  .TextString(Strings.Left(EntryType.ToString, 10)),
                                                  .TextString(Strings.Left(Description, 255)),
                                                  .TextString(Strings.Left(DataSource, 255)),
                                                  .Numeric(IIf(RecordCount = 0, DBNull.Value, RecordCount)),
                                                  Project.FullTableName(clsProject.enumTableTypes.Journal))
            num = .ExecuteNonQuery(sql)
        End With
        LastJournalDescription = Description
    End Sub

    ''' <summary>
    ''' Default description to be used for very next journal entry (will be cleared once it is used, but must be cleared using ClearJournalDescription in caller if dialog is cancelled)
    ''' </summary>
    Public Shared Property JournalDescription As String

    ''' <summary>
    ''' Description for prior journal entry (in case want to make multiple entries but not prompt user again)
    ''' </summary>
    Public Shared Property LastJournalDescription As String

    ''' <summary>
    ''' Clear the description that may have been in in prior dialog
    ''' </summary>
    Public Shared Sub ClearJournalDescription()
        JournalDescription = ""
    End Sub

    ''' <summary>
    ''' Prompt user for description that will be used when next journal entry is added
    ''' </summary>
    Public Shared Sub GetJournalDescription()
        Dim s As String = InputBox("Enter additional descriptive information that will be included in the Journal entry for this operation:", "Journal Entry", JournalDescription)
        If s <> "" Then JournalDescription = s
    End Sub

#End Region

    Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        Close()
    End Sub

    Private Sub btnHelp_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnHelp.Click
        ShowHelp(Me, "13")
    End Sub

    Private Sub btnOK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOK.Click
        With Project
            If chkHideForm.Checked Then MainWRDB.PromptJournal = clsWRDB.enumJournalPrompt.Never
            DialogResult = Windows.Forms.DialogResult.OK
            Close()
        End With
    End Sub

    Private Sub frmTracking_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
        SaveWindowPos(REGAPP, Me)
    End Sub

    Private Sub frmTracking_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Try
            GetWindowPos(REGAPP, Me)
            txtTableName.MaxLength = Project.dsWRDB.Tables("Journal").Columns("Table_Name").MaxLength
            txtDescription.MaxLength = Project.dsWRDB.Tables("Journal").Columns("Description").MaxLength
            txtSource.MaxLength = Project.dsWRDB.Tables("Journal").Columns("Source").MaxLength
            txtUserInit.MaxLength = Project.dsWRDB.Tables("Journal").Columns("User_Init").MaxLength
        Catch ex As Exception
            ErrorMsg(, ex)
        End Try
    End Sub

    ''' <summary>
    ''' Make first character upper case
    ''' </summary>
    Private Sub txt_TextChanged(sender As System.Object, e As System.EventArgs) Handles txtDescription.TextChanged, txtSource.TextChanged
        Dim txt As TextBox = sender
        If txt.Text.Length = 1 Then
            txt.Text = txt.Text.ToUpper
            txt.SelectionStart = 1
        End If
    End Sub
End Class
